package com.ruoyi.biz.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.biz.dto.LotteryDTO;
import com.ruoyi.biz.dto.LotteryLogDTO;
import com.ruoyi.biz.dto.LotteryPrizeDTO;
import com.ruoyi.biz.dto.LotteryResultDTO;
import com.ruoyi.biz.entity.*;
import com.ruoyi.biz.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.util.DateUtil;
import com.ruoyi.util.ValidateUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/wechat")
public class WechatLoginController extends BaseController {

    @Resource
    WechatUserService wechatUserService;
    @Resource
    LotteryService lotteryService;
    @Resource
    LotteryPrizeService lotteryPrizeService;
    @Resource
    LotteryResultService lotteryResultService;
    @Resource
    LotteryLogService lotteryLogService;
    @Resource
    LotteryUserService lotteryUserService;

    //公众号密钥
    private static String appId = "wx202f77313a8f3283";
    private static String secret = "88a866fc5555b7e08358645d64f509ef";
    private static String redirectUrl = "http://ghcj.natapp1.cc/wechat/authorize";
    private static String frontPage = "http://82.156.44.148:9090/vue-lottery/";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * @return
     */
    @GetMapping("/login")
    public ModelAndView wechat(String lotteryId) {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + appId + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=" + lotteryId + "#wechat_redirect";
        return new ModelAndView("redirect:" + url);
    }


    @GetMapping("/authorize")
    public String wechatCodeAuthorize(String code, String state, HttpServletRequest httpServletRequest, ModelMap mmap) {
        String urlTemplate = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        String url = String.format(urlTemplate, appId, secret, code);
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try {
            Response response = HTTP_CLIENT.newCall(request).execute();
            String responsedata = response.body().string();
//            logger.info("code:{},成功,{}", code, responsedata);
            JSONObject returnObject = JSONObject.parseObject(responsedata);
//            logger.info("本次获取到的openId:{}", returnObject.getString("openid"));
            String openId = returnObject.getString("openid");
            String unionId = returnObject.getString("openid");

            //获取微信昵称和性别
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + returnObject.getString("access_token")
                    + "&openid=" + openId
                    + "&lang=zh_CN";
            Request request2 = new Request.Builder()
                    .url(infoUrl)
                    .get()
                    .build();
            Response response2 = HTTP_CLIENT.newCall(request2).execute();
            String responsedata2 = response2.body().string();
            JSONObject returnObject2 = JSONObject.parseObject(responsedata2);

            //判断是否有当前用户存在,如果有则进行登录,没有则插入数据库后登录
            WechatUserDO qWechatUserDO = new WechatUserDO();
            qWechatUserDO.setOpenId(openId);
            List<WechatUserDO> wechatUserDOS = wechatUserService.queryList(qWechatUserDO);
            WechatUserDO wechatUserDO = new WechatUserDO();
            if (ValidateUtil.isEmpty(wechatUserDOS)) {
                wechatUserDO.setOpenId(openId);
                wechatUserDO.setUserId(IdUtils.simpleUUID().toUpperCase());
                wechatUserDO.setUnionId(unionId);
                wechatUserDO.setNickName(returnObject2.getString("nickname"));
                wechatUserDO.setSex(returnObject2.getString("sex"));
                wechatUserDO.setCrteTime(new Date());
                wechatUserService.insert(wechatUserDO);
            } else {
                wechatUserDO = wechatUserDOS.get(0);
            }
            HttpSession session = httpServletRequest.getSession();
            /*WechatEntity entity = (WechatEntity) session.getAttribute("weiUser");
            if (entity != null) {
                System.out.println(entity.toString());
                if (!entity.getOpenid().equals(openId)) {
                    //跳转到报错页
                }
            }*/

            //用户登录
            WechatEntity wechatEntity = WechatEntity.builder().openid(wechatUserDO.getOpenId()).userid(wechatUserDO.getUserId()).build();
            session.setAttribute("weiUser", wechatEntity);
            //判断页面跳转路径
            //如果是新用户----前往绑定页面
            //如果不是新用户,判断是否绑定过，没有绑定---前往绑定,绑定过---进抽奖页面

            mmap.put("openId", wechatEntity.getOpenid());
            mmap.put("userId", wechatEntity.getUserid());
            if (ValidateUtil.isEmpty(wechatUserDO.getTel()) || ValidateUtil.isEmpty(wechatUserDO.getPsnName())) {
                return "app/bind";
            }

            LotteryDTO lotteryDTO = new LotteryDTO();
            // todo 这里要判断的
//            lotteryDTO.setLotteryId(state);
            lotteryDTO.setQueryDate(new Date());
            lotteryDTO.setValiFlag("1");
            List<LotteryDO> lotteryDOS = lotteryService.queryList(lotteryDTO);
            if (ValidateUtil.isEmpty(lotteryDOS)) {
                return "app/error";
            }
            mmap.put("lotteryId", lotteryDOS.get(0).getLotteryId());
            mmap.put("lotteryContent", lotteryDOS.get(0).getLotteryContent());
            mmap.put("lotteryTime", DateUtil.date2Str(lotteryDOS.get(0).getBeginTime(), "yyyy年MM月dd日HH:mm") + "——" + DateUtil.date2Str(lotteryDOS.get(0).getEndTime(), "yyyy年MM月dd日HH:mm"));
            //奖品列表
            LotteryPrizeDTO lotteryPrizeDTO = new LotteryPrizeDTO();
            lotteryPrizeDTO.setLotteryId(lotteryDOS.get(0).getLotteryId());
            lotteryPrizeDTO.setValiFlag("1");
            List<LotteryPrizeDO> lotteryPrizeDOS = lotteryPrizeService.queryList(lotteryPrizeDTO);
            if (ValidateUtil.isEmpty(lotteryPrizeDOS)) {
                return "app/error";
            }
            for (LotteryPrizeDO item : lotteryPrizeDOS) {
                item.setPrizeImgBase64String(new String(item.getPrizeImgByte()));
                //这里就不放byte了，减少响应体，加快访问速度
                item.setPrizeImgByte(null);
            }
            mmap.put("lotteryPrizeDOS", lotteryPrizeDOS);
            return "app/index";
        } catch (IOException e) {
            logger.error("获取openid失败", e);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //跳转到报错页
        return "app/index";
    }

    @GetMapping("/bind")
    public String bind(HttpServletRequest httpServletRequest, ModelMap mmap) {
        mmap.put("contextPath", httpServletRequest.getRequestURL().toString().replace(httpServletRequest.getRequestURI(), ""));
        HttpSession session = httpServletRequest.getSession();
        WechatEntity entity = (WechatEntity) session.getAttribute("weiUser");
        if (entity != null) {
            mmap.put("openId", entity.getOpenid());
            mmap.put("userId", entity.getUserid());
        }
        return "app/bind";
    }

    @GetMapping("/appIndex")
    public String appIndex(HttpServletRequest httpServletRequest, ModelMap mmap) {
        mmap.put("contextPath", httpServletRequest.getRequestURL().toString().replace(httpServletRequest.getRequestURI(), ""));
        HttpSession session = httpServletRequest.getSession();
        WechatEntity entity = (WechatEntity) session.getAttribute("weiUser");
        if (entity != null) {
            mmap.put("openId", entity.getOpenid());
            mmap.put("userId", entity.getUserid());
        }
        return "app/index";
    }

    @PostMapping("/addBind")
    @ResponseBody
    public AjaxResult addBind(WechatUserDO wechatUserDO) {
        if (ValidateUtil.isEmpty(wechatUserDO)) {
            return error("入参不能为空");
        }
        if (ValidateUtil.isEmpty(wechatUserDO.getOpenId())) {
            return error("opId不能为空");
        }
        if (ValidateUtil.isEmpty(wechatUserDO.getUserId())) {
            return error("userId不能为空");
        }
        if (ValidateUtil.isEmpty(wechatUserDO.getTel())) {
            return error("联系电话不能为空");
        }
        if (ValidateUtil.isEmpty(wechatUserDO.getPsnName())) {
            return error("人员姓名不能为空");
        }
        LotteryUserDO qLotteryUserDO = new LotteryUserDO();
        qLotteryUserDO.setTel(wechatUserDO.getTel());
        qLotteryUserDO.setPsnName(wechatUserDO.getPsnName());
        qLotteryUserDO.setValiFlag("1");
        List<LotteryUserDO> lotteryUserDOS = lotteryUserService.queryList(qLotteryUserDO);
        if (ValidateUtil.isEmpty(lotteryUserDOS)) {
            return error("你填写的信息不在工会人员名单中，不能进行身份绑定！");
        } else if (!ValidateUtil.isEmpty(lotteryUserDOS.get(0).getUserId())) {
            return error("你填写的信息已经进行过身份绑定，不能重复绑定！");
        }
        return toAjax(wechatUserService.addBind(wechatUserDO, lotteryUserDOS.get(0)));
    }

    @PostMapping("/queryLotteryPrize")
    @ResponseBody
    public AjaxResult queryLotteryPrize(LotteryPrizeDTO lotteryPrizeDTO) {
        if (ValidateUtil.isEmpty(lotteryPrizeDTO)) {
            return error("入参不能为空！");
        }
        if (ValidateUtil.isEmpty(lotteryPrizeDTO.getLotteryId())) {
            return error("抽奖ID不能为空！");
        }
        lotteryPrizeDTO.setValiFlag("1");
        List<LotteryPrizeDO> list = lotteryPrizeService.queryList(lotteryPrizeDTO);
        for (LotteryPrizeDO item : list) {
            item.setPrizeImgBase64String(new String(item.getPrizeImgByte()));
            //这里就不放byte了，减少响应体，加快访问速度
            item.setPrizeImgByte(null);
        }
        return success(list);
    }

    @PostMapping("/queryLotteryLog")
    @ResponseBody
    public AjaxResult queryLotteryLog(LotteryLogDTO lotteryLogDTO, String openId) {
        if (ValidateUtil.isEmpty(lotteryLogDTO)) {
            return error("入参不能为空！");
        }
        if (ValidateUtil.isEmpty(lotteryLogDTO.getLotteryId())) {
            return error("抽奖ID不能为空！");
        }
        if (ValidateUtil.isEmpty(openId)) {
            return error("用户ID不能为空！");
        }
        WechatUserDO qWechatUserDO = new WechatUserDO();
        qWechatUserDO.setOpenId(openId);
        List<WechatUserDO> wechatUserDOS = wechatUserService.queryList(qWechatUserDO);
        if (ValidateUtil.isEmpty(wechatUserDOS)) {
            return error("未查询到用户信息！");
        } else if (wechatUserDOS.size() > 1) {
            return error("查询到多条用户信息！");
        }
        lotteryLogDTO.setTel(wechatUserDOS.get(0).getTel());
        lotteryLogDTO.setPsnName(wechatUserDOS.get(0).getPsnName());
        lotteryLogDTO.setValiFlag("1");
        List<LotteryLogDO> list = lotteryLogService.queryList(lotteryLogDTO);
        list = list.stream().filter(item -> !ValidateUtil.isEmpty(item.getLotteryResultId())).collect(Collectors.toList());
        return success(list);
    }

    @PostMapping("/getLotteryResult")
    @ResponseBody
    public AjaxResult getLotteryResult(LotteryResultDTO lotteryResultDTO, String openId) {
        if (ValidateUtil.isEmpty(lotteryResultDTO)) {
            return error("入参不能为空！");
        }
        if (ValidateUtil.isEmpty(lotteryResultDTO.getLotteryId())) {
            return error("抽奖ID不能为空！");
        }
        if (ValidateUtil.isEmpty(openId)) {
            return error("未获取到当前用户信息,请刷新页面!");
        }
        WechatUserDO qWechatUserDO = new WechatUserDO();
        qWechatUserDO.setOpenId(openId);
        List<WechatUserDO> wechatUserDOS = wechatUserService.queryList(qWechatUserDO);
        if (ValidateUtil.isEmpty(wechatUserDOS)) {
            return error("未获取到当前用户信息，请刷新页面!");
        } else if (wechatUserDOS.size() > 1) {
            return error("查询到多条用户信息，请联系管理员!");
        } else if (ValidateUtil.isEmpty(wechatUserDOS.get(0).getTel()) || ValidateUtil.isEmpty(wechatUserDOS.get(0).getPsnName())) {
            return error("用户未绑定手机号和姓名，请刷新页面!");
        }
        lotteryResultDTO.setTel(wechatUserDOS.get(0).getTel());
        lotteryResultDTO.setPsnName(wechatUserDOS.get(0).getPsnName());
        //查询抽奖活动信息
        LotteryDTO qLotteryDTO = new LotteryDTO();
        qLotteryDTO.setLotteryId(lotteryResultDTO.getLotteryId());
        qLotteryDTO.setQueryDate(new Date());
        qLotteryDTO.setValiFlag("1");
        List<LotteryDO> lotteryDTOS = lotteryService.queryList(qLotteryDTO);
        if (ValidateUtil.isEmpty(lotteryDTOS)) {
            return error("抽奖活动已过期！");
        }
        //查询抽奖记录信息
        LotteryLogDTO qLotteryLogDTO = new LotteryLogDTO();
        qLotteryLogDTO.setValiFlag("1");
        qLotteryLogDTO.setTel(lotteryResultDTO.getTel());
        qLotteryLogDTO.setPsnName(lotteryResultDTO.getPsnName());
        qLotteryLogDTO.setLotteryId(lotteryResultDTO.getLotteryId());
        List<LotteryLogDO> lotteryLogDTOS = lotteryLogService.queryList(qLotteryLogDTO);
        if (!ValidateUtil.isEmpty(lotteryLogDTOS)) {
            if (lotteryDTOS.get(0).getLotteryCntByPsn() <= lotteryLogDTOS.size()) {
                return error("您的抽奖次数已经用完！");
            }
            //如果已经中了奖，那就直接返回
            List<LotteryLogDO> filterResult = lotteryLogDTOS.stream().filter(item -> !ValidateUtil.isEmpty(item.getLotteryResultId())).collect(Collectors.toList());
            if (!ValidateUtil.isEmpty(filterResult)) {
                return error("您已经中过奖，无需再抽奖！");
            }
        }
        //查询奖品信息
        LotteryPrizeDTO qLotteryPrizeDTO = new LotteryPrizeDTO();
        qLotteryPrizeDTO.setValiFlag("1");
        qLotteryPrizeDTO.setLotteryId(lotteryResultDTO.getLotteryId());
        List<LotteryPrizeDO> lotteryPrizeDTOS = lotteryPrizeService.queryList(qLotteryPrizeDTO);
        if (ValidateUtil.isEmpty(lotteryPrizeDTOS)) {
            return error("系统出错，查询奖品信息失败！");
        }
        //定义写表实体类
        LotteryLogDTO lotteryLogDTO = new LotteryLogDTO();
        lotteryLogDTO.setLotteryId(lotteryResultDTO.getLotteryId());
        lotteryLogDTO.setTel(lotteryResultDTO.getTel());
        lotteryLogDTO.setPsnName(lotteryResultDTO.getPsnName());
        //组装基础数据
        lotteryLogDTO.setCrterId(lotteryResultDTO.getTel());
        lotteryLogDTO.setCrterName(lotteryResultDTO.getPsnName());
        lotteryLogDTO.setCrteTime(new Date());
        lotteryLogDTO.setOpterId(lotteryResultDTO.getTel());
        lotteryLogDTO.setOpterName(lotteryResultDTO.getPsnName());
        lotteryLogDTO.setOptTime(new Date());

        //查询中奖信息
        LotteryResultDTO qLotteryResultDTO = new LotteryResultDTO();
        qLotteryResultDTO.setValiFlag("1");
        qLotteryResultDTO.setLotteryId(lotteryResultDTO.getLotteryId());
        List<LotteryResultDO> lotteryResultDTOS = lotteryResultService.queryList(qLotteryResultDTO);

        //中奖flag，true代表中了，false代表没中
        boolean lotteryFlag = false;
        //能进入这个循环的，都是抽奖次数还未用完，且没抽中奖的
        for (LotteryPrizeDO lotteryPrizeDTO : lotteryPrizeDTOS) {
            //查询每个奖项的中奖信息
            List<LotteryResultDO> filterResult = lotteryResultDTOS.stream().filter(item -> lotteryPrizeDTO.getLotteryPrizeId().equals(item.getLotteryPrizeId())).collect(Collectors.toList());
            // 看看这个人是不是被添加的中奖人
            String tel = lotteryResultDTO.getTel();
            String psnName = lotteryResultDTO.getPsnName();
            List<LotteryResultDO> lotteryResultDTOSelected = filterResult.stream().filter(item -> tel.equals(item.getTel()) && psnName.equals(item.getPsnName()) && "1".equals(item.getLotteryResultType())).collect(Collectors.toList());
            //如果是被添加的中奖人，那就直接让他中
            if (!ValidateUtil.isEmpty(lotteryResultDTOSelected)) {
                lotteryFlag = true;
                lotteryLogDTO.setLotteryResultId(lotteryResultDTOSelected.get(0).getLotteryResultId());
                lotteryLogDTO.setLotteryPrizeTitle(lotteryResultDTOSelected.get(0).getLotteryPrizeTitle());
                lotteryLogDTO.setLotteryPrizeName(lotteryResultDTOSelected.get(0).getLotteryPrizeName());

                lotteryResultDTO = new LotteryResultDTO();
                BeanUtils.copyBeanProp(lotteryResultDTO, lotteryResultDTOSelected.get(0));
                lotteryResultDTO.setOpterId(tel);
                lotteryResultDTO.setOpterName(psnName);
                lotteryResultDTO.setOptTime(new Date());
                break;
            }
            //如果他不是被添加的中奖人，那就正常走中奖流程
            if (filterResult.size() < lotteryPrizeDTO.getPrizeCnt()) {
                int randomValue = (int) (Math.random() * 10000 + 1);
                if (randomValue <= lotteryPrizeDTO.getPrizeRate()) {
                    lotteryFlag = true;
                    lotteryLogDTO.setLotteryPrizeTitle(lotteryPrizeDTO.getLotteryPrizeTitle());
                    lotteryLogDTO.setLotteryPrizeName(lotteryPrizeDTO.getLotteryPrizeName());

                    lotteryResultDTO.setLotteryPrizeId(lotteryPrizeDTO.getLotteryPrizeId());
                    lotteryResultDTO.setLotteryPrizeTitle(lotteryPrizeDTO.getLotteryPrizeTitle());
                    lotteryResultDTO.setLotteryPrizeName(lotteryPrizeDTO.getLotteryPrizeName());
                    //中奖方式：2.抽中
                    lotteryResultDTO.setLotteryResultType("2");
                    //组装基础数据
                    lotteryResultDTO.setCrterId(lotteryResultDTO.getTel());
                    lotteryResultDTO.setCrterName(lotteryResultDTO.getPsnName());
                    lotteryResultDTO.setCrteTime(new Date());
                    lotteryResultDTO.setOpterId(lotteryResultDTO.getTel());
                    lotteryResultDTO.setOpterName(lotteryResultDTO.getPsnName());
                    lotteryResultDTO.setOptTime(new Date());
                    break;
                }
            }
        }

        int k = lotteryResultService.insertLotteryResultAndLog(lotteryResultDTO, lotteryLogDTO);
        if (lotteryFlag && k > 0) {
            return success(lotteryResultDTO);
        } else if (lotteryFlag) {
            return error("系统错误，抽奖失败！");
        } else {
            return success("很遗憾您没有中奖");
        }
    }
}
